package com.umpay.provdcs.net;

import org.apache.log4j.Logger;

import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.LinkedList;
import java.util.List;


public final class Writer extends Thread {

    private static Logger log = Logger.getLogger(Writer.class);

    private static List pool = new LinkedList();
    private static Notifier notifier = Notifier.getNotifier();

    public Writer() {
    }

    /**
     */
    public void run() {
        while (true) {
            try {
                SelectionKey key;
                synchronized (pool) {
                    while (pool.isEmpty()) {
                        pool.wait();
                    }
                    key = (SelectionKey) pool.remove(0);
                }

                // ����д�¼�
                write(key);
            } catch (Exception e) {
                continue;
            }
        }
    }


    public void write(SelectionKey key) {
        try {
            SocketChannel sc = (SocketChannel) key.channel();

            Response response = new Response(sc);

            byte[] output = ((Request) key.attachment()).getDataOutput();
            log.info("response to client:" + new String(output, "GBK"));

            notifier.fireOnWrite((Request) key.attachment(), response);

            sc.finishConnect();
            sc.socket().close();
            sc.close();

            notifier.fireOnClosed((Request) key.attachment());
        } catch (Exception e) {
            log.error("write thread error:" + e.getMessage());
            notifier.fireOnError("Error occured in Writer: " + e.getMessage());
        }
    }

    /**
     */
    public static void processRequest(SelectionKey key) {
        synchronized (pool) {
            pool.add(pool.size(), key);
            pool.notifyAll();
        }
    }
}
